#ifndef __ENGINE_REQUEST_CHECK_included
#define __ENGINE_REQUEST_CHECK_included

#include <boost/lexical_cast.hpp>
#include "Request.h"
#include "Session.h"
#include "Device.h"
#include "VersionTag.h"

namespace Engine {


class CRequestCheck : public CRequest
{
public:
	CRequestCheck(boost::asio::streambuf& data) :
		CRequest(string(COMMAND_CHECK), data)
	{
	}

	void HandleChecked() {
		
		boost::shared_ptr<JsonDocument> doc = ParseContentAsJson();
		if(!doc || !doc->IsArray()) return;

		for(JsonDocument::ValueIterator i = doc->Begin(); i != doc->End(); i++) {
			CVersionTag vt(*i);
			if(vt.mDeviceId >= 0) {
				mDevice->RemoveDeviceTags(vt);
			}
		}
	}

#ifdef SERVER
	virtual void DoRequest() {

		if(GetParameter(string("with-checked")).length() > 0) {
			HandleChecked();
		}

		boost::shared_ptr<CSession> session = mDevice->GetSession();

		JsonBuffer ss;
		JsonWriter writer(ss);
		
		string& target = GetParameter(string("target"));
		if(target == "all-tags") {
			writer.StartArray();
			session->GetSyncTagDescOfOtherDevices(mDevice->GetId(), writer);
			writer.EndArray();
		}
		else
		if(target == "devices") {
			writer.StartArray();
			session->GetDescOfOtherDevices(mDevice->GetId(), writer);
			writer.EndArray();
		}
		else {
			mDevice->GetAcceptedTagDesc(writer);
		}
		
		boost::shared_ptr<CResponse> r = InitResponse();
		r->SetStatus(RESPONSE_STATUS_OK);
		string content = ss.GetString();
		if(content.length() > 0) {
			r->SetContent(content, string(PACKAGE_CONTENT_TYPE_JSON));
		}

		mDevice->SendPackage(r);
	}
#endif
};
}
#endif // __ENGINE_REQUEST_CHECK_included